{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'周瑜'的词向量为：\n",
      " [-0.35357657 -0.16121455  0.2521911   1.2163538   0.03943549  0.31306806\n",
      " -0.21817212  0.80335295 -1.040092    0.20719509  0.36786985 -0.8814271\n",
      " -0.29908097 -0.37804994  0.13751124  0.16253571 -0.4189979  -0.12883227\n",
      " -0.45324153 -0.93680525]\n",
      "与'周瑜'相似度最高的10个词：\n",
      "[('孟获', 0.9365106821060181), ('孙策', 0.9292651414871216), ('陆逊', 0.9285946488380432), ('袁术', 0.9215583205223083), ('钟会', 0.9143669009208679), ('曹真', 0.9056782722473145), ('吕布', 0.9026312232017517), ('孔明自', 0.8939085602760315), ('孙夫人', 0.8916054368019104), ('关公', 0.8914663791656494)]\n",
      "'刘备'和'曹操'的相似度：0.7520554661750793\n",
      "在词'孙权/曹操/刘备/刘夫人'中，'刘备'与其他词不属于同一类\n"
     ]
    }
   ],
   "source": [
    "import jieba\n",
    "import re\n",
    "from gensim.models import Word2Vec\n",
    "#读取数据\n",
    "with open(r\"C:/Users/Administrator/Desktop/sanguo.txt\",encoding='utf-8') as f:\n",
    "    lines=[]\n",
    "    for line in f:\n",
    "        temp = jieba.lcut(line) #使用jieba进行分词\n",
    "        words = []\n",
    "        for i in temp:\n",
    "            i = re.sub(\"[\\s+\\.\\!\\/_,$%^*(+\\\"\\'””《》]+|[+——！，。？、~@#￥%……&*（）：；‘]+\", \"\", i)  #删除所有的标点符号\n",
    "            if len(i) > 0:\n",
    "                words.append(i)\n",
    "        if len(words) > 0:\n",
    "            lines.append(words)\n",
    "model = Word2Vec(lines, vector_size=20, window=2, min_count=3, epochs=7, negative=10,sg=1)   #训练模型\n",
    "print(\"'周瑜'的词向量为：\\n\",model.wv.get_vector('周瑜'))\n",
    "print(\"与'周瑜'相似度最高的10个词：\")\n",
    "print(model.wv.most_similar('周瑜',topn=10))\n",
    "print(\"'刘备'和'曹操'的相似度：{}\".format(model.wv.similarity('刘备','曹操')))\n",
    "words=\"孙权 曹操 刘备 孙夫人\"\n",
    "print(\"在词'孙权/曹操/刘备/刘夫人'中，'{}'与其他词不属于同一类\".format(model.wv.doesnt_match(words.split())))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
